<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>参加考试 - 在线考试系统</title>
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="/css/all.min.css">
    <style>
        :root {
            --primary: #4361ee;
            --secondary: #3f37c9;
            --student-accent: #4361ee;
            --card-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            --transition: all 0.3s ease;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f7fb;
            color: #333;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        /* 导航栏样式 */
        .navbar {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 0.8rem 1rem;
        }

        .navbar-brand {
            font-weight: 700;
            font-size: 1.5rem;
            display: flex;
            align-items: center;
        }

        .navbar-brand i {
            margin-right: 10px;
            font-size: 1.8rem;
        }

        .nav-link {
            color: rgba(255, 255, 255, 0.85) !important;
            font-weight: 500;
            padding: 0.5rem 1rem !important;
            border-radius: 4px;
            margin: 0 3px;
            transition: var(--transition);
        }

        .nav-link:hover, .nav-link.active {
            background-color: rgba(255, 255, 255, 0.15);
            color: white !important;
        }

        /* 主内容区域 */
        .main-content {
            flex: 1;
            padding: 2rem 0;
        }

        .page-header {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            box-shadow: var(--card-shadow);
            margin-bottom: 2rem;
            position: relative;
            overflow: hidden;
        }

        .page-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 5px;
            height: 100%;
            background-color: var(--student-accent);
        }

        .page-title {
            font-weight: 700;
            margin-bottom: 0.5rem;
            color: var(--student-accent);
        }

        .page-subtitle {
            color: #6c757d;
            margin-bottom: 0;
        }

        /* 计时器样式 */
        .timer {
            position: fixed;
            top: 100px;
            right: 20px;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white;
            padding: 1rem 1.5rem;
            border-radius: 15px;
            box-shadow: var(--card-shadow);
            z-index: 1000;
            min-width: 200px;
            text-align: center;
        }

        .timer h4 {
            margin: 0;
            font-weight: 700;
            font-size: 1.1rem;
        }

        .timer #timeRemaining {
            font-size: 1.2rem;
            font-weight: 700;
            color: #fff;
        }

        /* 题目容器样式 */
        .question-container {
            background: white;
            border-radius: 15px;
            padding: 2rem;
            box-shadow: var(--card-shadow);
            margin-bottom: 2rem;
            border-left: 5px solid var(--student-accent);
            transition: var(--transition);
        }

        .question-container:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
        }

        .question-title {
            font-weight: 700;
            margin-bottom: 1.5rem;
            color: var(--student-accent);
            font-size: 1.1rem;
        }

        .question-number {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white;
            padding: 0.3rem 0.8rem;
            border-radius: 20px;
            margin-right: 0.5rem;
            font-weight: 700;
        }

        .question-score {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            padding: 0.2rem 0.6rem;
            border-radius: 15px;
            font-size: 0.9rem;
            font-weight: 600;
        }

        .options-container {
            margin-left: 1rem;
        }

        .form-check {
            margin-bottom: 0.75rem;
            padding: 0.75rem;
            border-radius: 10px;
            transition: var(--transition);
        }

        .form-check:hover {
            background-color: rgba(67, 97, 238, 0.05);
        }

        .form-check-input {
            width: 1.2rem;
            height: 1.2rem;
            margin-top: 0.1rem;
        }

        .form-check-input:checked {
            background-color: var(--student-accent);
            border-color: var(--student-accent);
        }

        .form-check-label {
            margin-left: 0.5rem;
            font-weight: 500;
            cursor: pointer;
        }

        .form-control {
            border-radius: 10px;
            border: 2px solid #e9ecef;
            padding: 0.75rem 1rem;
            transition: var(--transition);
        }

        .form-control:focus {
            border-color: var(--student-accent);
            box-shadow: 0 0 0 0.2rem rgba(67, 97, 238, 0.25);
        }

        /* 按钮样式 */
        .action-buttons {
            background: white;
            border-radius: 15px;
            padding: 2rem;
            box-shadow: var(--card-shadow);
            text-align: center;
            margin-bottom: 2rem;
        }

        .btn {
            border-radius: 10px;
            font-weight: 600;
            padding: 0.75rem 2rem;
            margin: 0 0.5rem;
            transition: var(--transition);
            font-size: 1rem;
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--student-accent), #3a0ca3);
            border: none;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(67, 97, 238, 0.4);
        }

        .btn-success {
            background: linear-gradient(135deg, #28a745, #20c997);
            border: none;
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(40, 167, 69, 0.4);
        }

        /* 页脚样式 */
        .footer {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white;
            padding: 2rem 0;
            margin-top: auto;
        }

        .footer-title {
            font-weight: 700;
            margin-bottom: 1rem;
            font-size: 1.25rem;
        }

        .footer-links {
            list-style: none;
            padding: 0;
        }

        .footer-links li {
            margin-bottom: 0.5rem;
        }

        .footer-links a {
            color: rgba(255, 255, 255, 0.8);
            text-decoration: none;
            transition: var(--transition);
        }

        .footer-links a:hover {
            color: white;
            text-decoration: underline;
        }

        .copyright {
            text-align: center;
            padding-top: 1.5rem;
            margin-top: 1.5rem;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            color: rgba(255, 255, 255, 0.7);
            font-size: 0.9rem;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .navbar-brand {
                font-size: 1.2rem;
            }

            .page-header {
                padding: 1rem;
            }

            .timer {
                position: relative;
                top: auto;
                right: auto;
                margin-bottom: 1rem;
                min-width: auto;
            }

            .question-container {
                padding: 1.5rem;
            }

            .action-buttons {
                padding: 1.5rem;
            }

            .btn {
                margin: 0.25rem;
                padding: 0.6rem 1.5rem;
            }
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container">
            <a class="navbar-brand" href="/student/home">
                <i class="fas fa-graduation-cap"></i>在线考试系统
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link active" href="/home/manage"><i class="fas fa-home"></i> 主页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/student/exam/list"><i class="fas fa-pen-alt"></i> 考试信息</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/student/score/analysis"><i class="fas fa-chart-line"></i> 成绩分析</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/student/resources"><i class="fas fa-book-open"></i> 学习资源</a>
                    </li>
                </ul>

                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/student/profile/manage">
                            <i class="fas fa-user-circle"></i> 个人信息
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/logout">
                            <i class="fas fa-sign-out-alt"></i> 退出登录
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- 主内容区域 -->
    <div class="main-content">
        <div class="container">
            <div class="timer">
                <h4><i class="fas fa-clock me-2"></i>剩余时间</h4>
                <div id="timeRemaining"></div>
            </div>
            
            <div class="page-header">
                <h2 class="page-title"><i class="fas fa-pen-alt me-2"></i>考试题目</h2>
                <p class="page-subtitle">请仔细阅读题目，认真作答</p>
            </div>
            
            <form id="examForm">
                <input type="hidden" id="recordId" th:value="${studentExam.recordId}">
                <input type="hidden" id="examId" th:value="${studentExam.examId}">
                <input type="hidden" id="duration" th:value="${duration}">
                
                <div th:each="question, stat : ${questions}" class="question-container">
                    <div class="question-title">
                        <span class="question-number" th:text="${stat.count}"></span>
                        <span th:text="${question.content}"></span>
                        <span class="question-score" th:text="'分值：' + ${question.score} + '分'"></span>
                    </div>
                    
                    <div th:if="${question.type == 'choice'}" class="options-container">
                        <div th:each="option, idx : ${question.optionList}" class="form-check">
                            <input class="form-check-input" type="radio" 
                                   th:name="'answer_' + ${question.questionId}"
                                   th:value="${option}"
                                   th:id="'q' + ${question.questionId} + '_' + ${idx.index}">
                            <label class="form-check-label" th:for="'q' + ${question.questionId} + '_' + ${idx.index}"
                                   th:text="${option}"></label>
                        </div>
                    </div>
                    
                    <div th:if="${question.type == 'fill'}" class="form-group">
                        <input type="text" class="form-control" 
                               th:name="'answer_' + ${question.questionId}"
                               th:placeholder="'请填写答案'">
                    </div>
                    
                    <div th:if="${question.type == 'essay'}" class="form-group">
                        <textarea class="form-control" rows="4"
                                  th:name="'answer_' + ${question.questionId}"
                                  th:placeholder="'请填写答案'"></textarea>
                    </div>
                </div>
                
                <div class="action-buttons">
                    <button type="button" class="btn btn-primary" onclick="saveAnswers()">
                        <i class="fas fa-save me-2"></i>保存答案
                    </button>
                    <button type="button" class="btn btn-success" onclick="submitExam()">
                        <i class="fas fa-paper-plane me-2"></i>提交考试
                    </button>
                </div>
            </form>
        </div>
    </div>

<!-- 页脚 -->
<footer class="footer">
    <div class="container text-center py-4">
        <a href="https://gitee.com/sorrymaker04/onlineexam-workload" target="_blank"><i class="fab fa-github fa-2x"></i></a>
        <div class="copyright mt-2">
            &copy; 2025 版权所有 北城在线考试系统小组 12 Team
        </div>
    </div>
</footer>

    <script src="/js/bootstrap.bundle.min.js"></script>
    <script src="/js/jquery.min.js"></script>
    <script>
        let recordId = null;
        let examId = document.getElementById('examId') ? document.getElementById('examId').value : null;
        let duration = null;
        let startTime = null;

        // 页面加载时获取考试信息和已保存答案
        $(document).ready(function () {
            examId = $('#examId').val() || $('[id=examId]').val();
            if (!examId) {
                alert('页面参数错误');
                return;
            }
            // 获取考试信息
            $.get('/student/exam/info/' + examId, function (info) {
                recordId = info.recordId;
                duration = info.duration;
                startTime = info.startTime;
                $('#recordId').val(recordId);
                $('#duration').val(duration);

                // 初始化倒计时
                updateTimer(startTime, duration);

                // 获取并回显已保存答案
                $.get('/student/exam/answers/' + recordId, function (answers) {
                    if (answers && answers.length > 0) {
                        answers.forEach(function (ans) {
                            let qid = ans.questionId;
                            let val = ans.answer;
                            // 选择题
                            let radio = $('input[type=radio][name="answer_' + qid + '"]');
                            if (radio.length > 0) {
                                radio.each(function () {
                                    if ($(this).val() === val) {
                                        $(this).prop('checked', true);
                                    }
                                });
                            }
                            // 填空题
                            let input = $('input[type=text][name="answer_' + qid + '"]');
                            if (input.length > 0) {
                                input.val(val);
                            }
                            // 简答题
                            let textarea = $('textarea[name="answer_' + qid + '"]');
                            if (textarea.length > 0) {
                                textarea.val(val);
                            }
                        });
                    }
                });
            });
        });

        // 倒计时函数
        function updateTimer(startTimeStr, durationMin) {
            let endTime = new Date(new Date(startTimeStr.replace('T', ' ').replace(/-/g, '/')).getTime() + durationMin * 60 * 1000);
            function update() {
                let now = new Date();
                let distance = endTime - now;
                if (distance < 0) {
                    $('#timeRemaining').html('考试时间已结束');
                    submitExam(true);
                    clearInterval(timer);
                    return;
                }
                let hours = Math.floor(distance / (1000 * 60 * 60));
                let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                let seconds = Math.floor((distance % (1000 * 60)) / 1000);
                $('#timeRemaining').html(hours + '小时 ' + minutes + '分钟 ' + seconds + '秒');
            }
            update();
            let timer = setInterval(update, 1000);
        }

        // 保存答案
        function saveAnswers() {
            if (!recordId) return;
            const answers = [];
            const questionIds = new Set();
            document.querySelectorAll('[name^="answer_"]').forEach(input => {
                const questionId = input.name.split('_')[1];
                if (questionIds.has(questionId)) return;
                let answer = '';
                if (input.type === 'radio') {
                    const checked = document.querySelector(`input[name="answer_${questionId}"]:checked`);
                    if (checked) answer = checked.value;
                    else return;
                } else {
                    answer = input.value;
                }
                answers.push({
                    recordId: recordId,
                    questionId: questionId,
                    answer: answer
                });
                questionIds.add(questionId);
            });
            $.ajax({
                url: '/student/exam/save',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(answers),
                success: function(response) {
                    showNotification('答案已保存', 'success');
                },
                error: function() {
                    showNotification('保存失败，请重试', 'error');
                }
            });
        }

        // 提交考试
        function submitExam(isAutoSubmit = false) {
            if (!recordId) return;
            if (!isAutoSubmit && !confirm('确定要提交考试吗？提交后将无法修改答案。')) {
                return;
            }
            const answers = [];
            const questionIds = new Set();
            document.querySelectorAll('[name^="answer_"]').forEach(input => {
                const questionId = input.name.split('_')[1];
                if (questionIds.has(questionId)) return;
                let answer = '';
                if (input.type === 'radio') {
                    const checked = document.querySelector(`input[name="answer_${questionId}"]:checked`);
                    if (checked) answer = checked.value;
                    else answer = ''; // 未答题目传空字符串
                } else {
                    answer = input.value || ''; // 填空题和简答题未答时传空字符串
                }
                answers.push({
                    recordId: recordId,
                    questionId: questionId,
                    answer: answer
                });
                questionIds.add(questionId);
            });
            $.ajax({
                url: '/student/exam/submit',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(answers),
                success: function(response) {
                    if (isAutoSubmit) {
                        showNotification('考试时间已到，系统已自动提交考试', 'warning');
                    } else {
                        showNotification('考试已提交', 'success');
                    }
                    setTimeout(() => {
                        window.location.href = '/student/exam/list';
                    }, 1500);
                },
                error: function() {
                    showNotification('提交失败，请重试', 'error');
                }
            });
        }

        // 显示通知
        function showNotification(message, type) {
            let alertClass = 'alert-info';
            let icon = 'fas fa-info-circle';
            
            if (type === 'success') {
                alertClass = 'alert-success';
                icon = 'fas fa-check-circle';
            } else if (type === 'error') {
                alertClass = 'alert-danger';
                icon = 'fas fa-exclamation-circle';
            } else if (type === 'warning') {
                alertClass = 'alert-warning';
                icon = 'fas fa-exclamation-triangle';
            }
            
            const notification = $(`
                <div class="alert ${alertClass} alert-dismissible fade show position-fixed" 
                     style="top: 20px; right: 20px; z-index: 9999; min-width: 300px;">
                    <i class="${icon} me-2"></i>${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            `);
            $('body').append(notification);
            setTimeout(() => {
                notification.alert('close');
            }, 3000);
        }

        // 定时保存答案
        setInterval(saveAnswers, 300000); // 每5分钟自动保存一次
    </script>
</body>
</html> 